package top.buaarobot.webserver.web.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.buaarobot.webserver.domain.User;
import top.buaarobot.webserver.repository.UserRepository;
import org.springframework.web.bind.annotation.*;
import top.buaarobot.webserver.service.UserService;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/user")
public class UserResource {

    private final UserRepository userRepository;
    private final UserService userService;

    public UserResource(UserRepository userRepository, UserService userService) {
        this.userRepository = userRepository;
        this.userService = userService;
    }

    @PostMapping("/register")
    public String UserRegister(@RequestBody JSONObject json) {
        User user = (User) JSONObject.toJavaObject(json, User.class);
        System.out.println("[POST /api/user/register]: " + user.getUsername());
        if(userRepository.findByUsername(user.getUsername()).size()!=0){
            return "Existed";
        }
        user.setAuthority(";");
        this.userRepository.saveAndFlush(user);
        return "Success";
    }

    @PostMapping("/login")
    public User UserLogin(@RequestBody JSONObject json) {
        System.out.println("[POST /api/user/login]: " + json.toString());
        List<User> userList = this.userRepository.findByUsername((json.getString("username")));
        if(userList.size() > 0){
            if(userList.get(0).getPassword().equals(json.getString("password"))) {
                return userList.get(0);
            }
        }
        return null;
    }

    @GetMapping("/info/{count}")
    public JSONArray getActiveUsers(@PathVariable("count") Integer count){
        JSONArray result = userService.getActiveUsers(count);
        return result;
    }



}
